package com.fyl.leetcode.DFS.isLand;

/**
 * @author:fyl
 * @date 2021/5/17 16:13
 * @Modified By:
 * @Modified Date:
 * @Description: 200
 * 给你一个由'1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
 * 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
 * 此外，你可以假设该网格的四条边均被水包围。
 * 输入：grid = [
 * ["1","1","1","1","0"],
 * ["1","1","0","1","0"],
 * ["1","1","0","0","0"],
 * ["0","0","0","0","0"] ]
 * 输出：1
 */
public class NumIslands {
    //上下左右的方向数组。
    private int[][] direction = {{0,1},{0,-1},{1,0},{-1,0}};
    public int numIslands(char[][] grid) {
        int isIslandNum = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j]=='1'){
                    isIsland(i,j,grid);
                    isIslandNum++;
                }
            }
        }
        return isIslandNum;
    }

    private void isIsland(int i, int j, char[][] grid) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] != '1') {
            return;
        }
        //标记为已经遍历过的陆地格子。如果用沉岛，将1设置为0，则无法区分海洋格子和已经遍历过的陆地格子
        //本题两种方法都可
        grid[i][j] = '2';
        for (int[] dir : direction) {
            isIsland(i+dir[0],j+dir[1],grid);
        }
    }
}
